//单词搜索
//测试链接：https://leetcode.cn/problems/word-search/
public class Exist {
    boolean[][] vis;
    int m, n;
    char[] word;

    public boolean exist(char[][] board, String _word) {
        m = board.length;
        n = board[0].length;
        word = _word.toCharArray();
        vis = new boolean[m][n];
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word[0]) {
                    vis[i][j] = true;
                    if (dfs(board, i, j, 1))
                        return true;
                    vis[i][j] = false;
                }
            }
        return false;
    }

    int[] dx = { 0, 0, 1, -1 };
    int[] dy = { 1, -1, 0, 0 };

    public boolean dfs(char[][] board, int i, int j, int pos) {
        if (pos == word.length) {
            return true;
        }
        // 上下左右去匹配 word[pos]
        // 利⽤向量数组，⼀个 for 搞定上下左右四个⽅向
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && board[x][y] == word[pos]) {
                vis[x][y] = true;
                if (dfs(board, x, y, pos + 1))
                    return true;
                vis[x][y] = false;
            }
        }
        return false;
    }
}
